<template>
  <div :class="`${xvueNameSpace}`">
    <div
      v-loading="isLoading"
      class="config-panel"
    >
      <div
        class="container"
        :class="xvueTheme"
      >
        <el-tabs v-model="activeName">
          <el-tab-pane
            :label="$demoi18n('panel.tab.baseInfo')"
            name="zero"
          >
            <HelpManual />
            <!-- xvue注册的组件 -->
            <xvp-base-info
              ref="xVueBaseInfo"
              :is-hide-share-parameter="true"
              :widget-instance-id="widgetInstanceId"
              :is-exist-config="true"
              :is-hide-save-button="true"
            />
          </el-tab-pane>
          <el-tab-pane
            :label="propertyLabel"
            name="first"
          >
            <panel-property
              ref="panel_property"
              :config="config"
              :widget-instance-id="widgetInstanceId"
              :widget="widget"
            />
          </el-tab-pane>
          <el-tab-pane
            :label="$demoi18n('panel.tab.data')"
            name="second"
          >
            <panel-data
              ref="panel_data"
              :config="config"
              :org-config="orgConfig"
              :widget-instance-id="widgetInstanceId"
              :data-source-type-options="isAurora ? auroraDataSourceTypeOptions : dataSourceTypeOptions"
              :is-aurora="isAurora"
              :dataForm="dataForm"
            />
          </el-tab-pane>
          <el-tab-pane
            :label="$demoi18n('panel.tab.linkage')"
            name="third"
          >
            <panel-linkage
              ref="panel_linkage"
              :config="config"
              :widget-instance-id="widgetInstanceId"
            />
          </el-tab-pane>
        </el-tabs>
        <div class="save_box">
          <el-button
            type="primary"
            class="saveBtn"
            @click.stop="saveAllData()"
          >
            {{ $demoi18n('panel.button.apply') }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { dataSourceTypeOptions, auroraDataSourceTypeOptions } from '@/common/panel_config';
import PanelProperty from './panel-property';
import PanelData from './panel-data';
import PanelLinkage from '@/components/panel-linkage-new/panel-linkage';
import configPanelBase from '@/mixin/config-panel-base.js';
import xtagBase from '../../panel-data/xtag-base';
import HelpManual from '@/components/common/help-manual/help-manual.vue';

export default {
  name: 'PropertyPanelCommonXMultipleY',
  components: {
    PanelProperty,
    PanelData,
    PanelLinkage,
    HelpManual,
  },
  mixins: [configPanelBase],
  props: ['config', 'orgConfig', 'widgetInstanceId', 'widget'],
  data() {
    return {
      isLoading: false,
      activeName: window.isLocalEnv ? 'first' : 'zero',
      dataSourceTypeOptions: dataSourceTypeOptions,
      auroraDataSourceTypeOptions,
      isAurora: this.$platformName === 'Aurora',

      // 数据页签中的表单
      dataForm: {
        apis: [
          {
            dataSourceType: '',
            dataSource: '',
            dataTable: '',
            redisKey: '',
            apiCode: '',
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  methods: {
    async saveAllData() {
      // 初始化保存条件
      this.isCanSave = true;
      const valid = await this.checkValid();
      if (!valid) {
        return;
      }

      const { xVueBaseInfo, useSharedConfig, xVueBaseInfoCanSave } = this.getXVueBaseInfo();

      // 如果有用到xvue 的 共享配置/关联配置，必须得满足保存条件
      if (useSharedConfig && !xVueBaseInfoCanSave) {
        this.$message({
          message: this.$demoi18n('message.relatedFieldIsEmpty'),
          type: 'warning',
        });
        return;
      }

      const property = this.$refs['panel_property'].form;
      const data = this.$refs['panel_data'].form;
      const customCalculationXTag = {};
      const { mappingOptionsFinal } = this.$refs['panel_data'];
      Object.entries(mappingOptionsFinal).map(([key]) => {
        customCalculationXTag[key] = [];
        const options = mappingOptionsFinal[key];
        options.forEach(item => {
          if (item.type && (item.type === 'add' || item.type === 'edit')) {
            customCalculationXTag[key].push(item);
          }
        });
      });
      data.customCalculationXTag = customCalculationXTag;
      const linkage = this.getLinkage();
      this.updateEmitParamsObj(linkage);
      if (window.parent.saveVmConfig) {
        setTimeout(() => {
          window.parent.saveVmConfig({ property, data, events: linkage });
        }, 50);
      }

      this.checkLoading();

      // 没有用到xvue 的 共享配置/关联配置，要校验数据
      if (!useSharedConfig) {
        this.checkConfigData(data);
      }
      if (!this.isCanSave) {
        return;
      }
      this.saveProperties({ property, data, linkage });
    },

    // 检查数据页签配置字段是否为空
    checkConfigData(data) {
      const { datas } = data;
      datas.forEach(dataItem => {
        dataItem.forEach(item => {
          if (this.isCanSave) {
            if (!item.skipVerification) {
              if (!item.mapping) {
                this.isCanSave = false;
                this.$message({
                  message: `${$demoi18n('message.mappingFieldEmpty')} : ${item.field}`,
                  type: 'warning',
                });
              }
            }
          }
        });
      });
    },

    /*
     * 组件config国际化修正
     * 因为保存在config里面，切换语言后，国际化还是之前语言的显示，需要手工修正
     */
    updateConfigI18n() {
      this.config.config.data.datas.forEach(n => {
        n[1].explain = this.$demoi18n('panelData.explain.horizontalAxis');
        n[2].explain = this.$demoi18n('panelData.explain.value');
        n[3].explain = this.$demoi18n('word.category');
        n[4] && (n[4].explain = this.$demoi18n('panelData.explain.scatterSizeBasis'));
      });

      const xTag = this.config.config && this.config.config.data && this.config.config.data.customCalculationXTag;
      if (xTag) {
        Object.entries(xTag).map(([i]) => {
          xTag[i].forEach(n => {
            let label = n.option_label;
            switch (n.type) {
              case 'add':
                label = this.$demoi18n('word.addCustomCalculation');
                break;
              default:
                break;
            }
            n['option_label'] = label;
          });
        });
      }
    },
  },
};
</script>
<style lang="less" scoped>
// 配置面板通用样式，主要有明亮风格和蓝黑，样式名需一致
@import '../../common/less/config-panel.less';
</style>
